<?php

class OneExt extends CActiveRecord {
	protected $_ext = NULL;

	public static function model($className = __CLASS__ ) {
		return parent::model($className);
	}

	public function tableName() {
		return "one_ext";
	}

	private function fetchExt() {
		$this->_ext = json_decode($this->ext,true);
		if ($this->_ext === FALSE) {
			Log::fatal("one_ext[id=$this->id] is strange.", array("ext"=>$objOneExt->ext));
			throw new Exception("one_ext[id=$this->id] is strange!");
		}
	}

	public function get($key) {
		if (is_null($this->_ext)) {
			$this->fetchExt();
		}
		return isset($this->_ext[$key]) ? $this->_ext[$key] : NULL;
	}

	public function set($key,$value) {
		if (is_null($this->_ext)) {
			$this->fetchExt();
		}
		$this->_ext[$key] = $value;
	}

	public function save() {
		if (is_array($this->_ext)) {
			$this->ext = json_encode($this->_ext);
		}
		return parent::save();
	}

	public function getDetail() {
		if (is_null($this->_ext)) {
			$this->fetchExt();
		}
		return $this->_ext;

	}

}

class One extends CActiveRecord {

	const TYPE_NORMAL = 0;
	const TYPE_SHOP   = 1;
	const TYPE_BANK   = 2;
	const TYPE_SYSTEM = 100;

	protected $_oneExt = NULL;

	public static function model($className = __CLASS__ ) {
		return parent::model($className);
	}

	public function tableName() {
		return "one";
	}

	public function relations() {
		return array(
			'ext' => array(self::HAS_ONE, "OneExt", "id"),
		);
	}

	private function fetchExt() {
		$this->_oneExt = OneExt::model()->findByPk($this->id);
		if (is_null($this->_oneExt)) {
			$this->_oneExt = new OneExt();
			$this->_oneExt->id = $this->id;
			$this->_oneExt->ext = "[]";
		}
	}

	public function get($key) {
		if (is_null($this->_oneExt)) $this->fetchExt();
		return $this->_oneExt->get($key);
	}

	public function set($key,$value) {
		if (is_null($this->_oneExt)) $this->fetchExt();
		$this->_oneExt->set($key,$value);
	}

	public function getDetail() {
		if (is_null($this->_oneExt)) $this->fetchExt();
		return $this->_oneExt->getDetail();
	}

	public function save() {
		return parent::save() && ((!$this->_oneExt instanceof OneExt) || $this->_oneExt->save());
	}
}

